<template>
  <div class="app-container">
    <xr-header
      :label="typeObj.name"
      :icon-class="`wk wk-${typeObj.icon}`"
      :icon-color="typeObj.color"
      placeholder="请输入仓库名称/仓库编码"
      show-search
      @search="handleSearch">
      <template slot="ft">
        <el-button
          v-if="canSave"
          icon="el-icon-plus"
          type="primary"
          class="xr-btn--orange"
          @click="handleCommand('create')">
          新建仓库
        </el-button>

        <el-dropdown
          v-if="moreTypes && moreTypes.length > 0"
          trigger="click"
          @command="handleCommand">
          <el-button icon="el-icon-more"/>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="(item, index) in moreTypes"
              :key="index"
              :icon="item.icon | wkIconPre"
              :command="item.type">{{ item.name }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </template>
    </xr-header>

    <div class="container">
      <list-table-header
        ref="xrTableHeader"
        :selects="selectedList"
        :handles="controlBtnGroup"
        hide-filter
        @command="handleCommand" />

      <el-table
        v-loading="loading"
        :data="dataList"
        :height="tableHeight"
        stripe
        border
        highlight-current-row
        style="width: 100%;"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="handleSort"
        @header-dragend="handleDragend">
        <el-table-column
          show-overflow-tooltip
          type="selection"
          align="center"
          width="55" />
        <template v-for="(item, index) in fieldList">
          <el-table-column
            v-if="!item.isHide && item.formType === 'pic'"
            :key="index"
            :label="item.name"
            :fixed="item.fixed"
            :prop="item.fieldName"
            width="112"
            header-align="left"
            align="center">
            <template slot-scope="scope">
              <template
                v-if="scope.row[scope.column.property] instanceof Array">
                <adapter-image
                  v-for="(valObj, valIndex) in scope.row[scope.column.property]"
                  :key="valIndex"
                  :src="valObj.url"
                  @click.stop="previewImage(scope, valIndex)" />
              </template>
              <template v-else>
                <adapter-image
                  :src="scope.row[scope.column.property]"
                  @click.stop="previewImage(scope, null)" />
              </template>
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="!item.isHide"
            :key="index"
            :fixed="item.fixed"
            :prop="item.fieldName"
            :label="item.name"
            :width="item.width || ''"
            :min-width="100"
            :sortable="item.sortable || false"
            :formatter="item.formatter || null"
            :class-name="item.canVisit ? 'can-visit--underline' : ''"
            show-overflow-tooltip />
        </template>
        <el-table-column v-if="dataList.length === 0" />
      </el-table>

      <div class="p-contianer">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size.sync="pageSize"
          :total="total"
          :pager-count="5"
          class="p-bar"
          background
          layout="prev, pager, next, sizes, total, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>
    </div>

    <create-house
      v-if="showCreate"
      :edit-data="editData"
      @update="handleRefresh"
      @close="showCreate = false" />
  </div>
</template>

<script>
import {
  jxcWarehouseQueryPageListAPI,
  jxcWarehouseDeleteByIdsAPI,
  jxcWarehouseSetTurnByIdsAPI,
  jxcWarehouseAllExportExcelAPI
} from '@/api/jxc/warehouse'

import CreateHouse from './Create'

import TableMixin from '../../mixins/Table'

export default {
  name: 'SaleOrderIndex',
  components: {
    CreateHouse
  },
  mixins: [TableMixin],
  data() {
    return {
      fieldList: [
        { fieldName: 'warehouseName', name: '仓库名称' },
        { fieldName: 'warehouseCode', name: '仓库编码' },
        { fieldName: 'warehouseAddress', name: '仓库地址' },
        { fieldName: 'warehouseIsuse', name: '状态' },
        { fieldName: 'createUserName', name: '创建人' },
        { fieldName: 'createTime', name: '创建时间' },
        { fieldName: 'updateTime', name: '更新时间' }
      ],
      editData: {},

      type: 'jxc_warehouse'
    }
  },
  computed: {
    moreTypes() {
      const temps = []
      // { type: 'enter', name: '导入', icon: 'import' },
      if (this.canExport) {
        temps.push({ type: 'out', name: '导出', icon: 'export' })
      }
      return temps
    }
  },
  watch: {
    selectedList: {
      handler(val) {
        const arr = [
          // { command: 'export', label: '导出选中', icon: 'export' }
        ]
        const enableItem = { command: 'enable', label: '启用', icon: 'enable' }
        const disableItem = { command: 'disable', label: '停用', icon: 'disable' }
        const enableNum = val.filter(o => o.warehouseIsuse == 1).length
        if (enableNum === val.length && this.jxc.warehouse.spst) {
          arr.push(disableItem)
        }
        const disableNum = val.filter(o => o.warehouseIsuse == 0).length
        if (disableNum === val.length && this.jxc.warehouse.spst) {
          arr.push(enableItem)
        }
        if (val.length === 1 && this.jxc.warehouse.update) {
          arr.push({
            command: 'update',
            label: '编辑',
            icon: 'edit'
          })
        }
        if (this.jxc.warehouse.delete) {
          arr.push({
            command: 'delete',
            label: '删除',
            icon: 'delete'
          })
        }

        this.controlBtnGroup = arr
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.fieldList.forEach(item => {
      if (item.fieldName === 'warehouseIsuse') {
        item.formatter = (row, column, cellValue, index) => {
          return cellValue == 1 ? '已启用' : '已停用'
        }
      } else {
        item.formatter = (row, column, cellValue, index) => {
          return cellValue || '--'
        }
      }
    })
  },
  methods: {
    getDataList(params = {}, refresh = false) {
      this.loading = true
      if (refresh) {
        this.currentPage = 1
      }
      this.otherParams = params
      jxcWarehouseQueryPageListAPI({
        page: this.currentPage,
        limit: this.pageSize,
        warehouseName: params.search || ''
      }).then(res => {
        this.dataList = res.data.list
        this.total = res.data.totalRow
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    handleCommand(command) {
      switch (command) {
        case 'create':
          // 新建
          this.editData = {}
          this.showCreate = !this.showCreate
          break
        case 'update':
          // 编辑
          this.editData = this.selectedList[0]
          this.showCreate = !this.showCreate
          break
        case 'disable':
          this.handleSetUse(0, '停用')
          break
        case 'enable':
          this.handleSetUse(1, '启用')
          break
        case 'delete':
          this.handleDelete()
          break
        case 'out':
          this.allExportExcel(jxcWarehouseAllExportExcelAPI)
          break
      }
    },

    /**
     * 表格点击事件
     * @param row 被点击的行数据
     * @param field 被点击的字段
     */
    handleTableClick(row, field) {
      this.showDetail = true
    },

    handleDelete() {
      this.$confirm(`确定要删除这些仓库吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        jxcWarehouseDeleteByIdsAPI({
          ids: this.selectedList.map(o => o.warehouseId).join(',')
        }).then(() => {
          this.$message.success('删除成功')
          this.getDataList(this.otherParams)
        }).catch(() => {})
      }).catch(() => {
        this.$message.info('已取消')
      })
    },

    handleSetUse(status, label) {
      this.$confirm(`确定要${label}这些仓库吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        jxcWarehouseSetTurnByIdsAPI({
          ids: this.selectedList.map(o => o.warehouseId).join(','),
          isuse: status
        }).then(() => {
          this.$message.success('操作成功')
          this.getDataList(this.otherParams)
        }).catch(() => {})
      }).catch(() => {
        this.$message.info('已取消')
      })
    }
  }
}
</script>

<style scoped lang="scss">
  @import "../../styles/index";
</style>
